const http = require("http");
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const httpServer = http.createServer(app);
const io = socketIo(httpServer);// 支持socket
app.use(express.json());
const userList = {};// 将socket.id作为属性名，属性值是用户名。
io.on("connection",function(socket){
	socket.on("intoRoom",function(userName){
		userList[socket.id] = userName;
		// 进入
		io.emit("upRoom",userName,Object.keys(userList).length,true);
	});
	socket.on("say",function(userName,context){
		// 告诉所有人userName说了哪些话。
		io.emit("roomSay",userName,context);
	})
	socket.on("disconnect",function(){
		const userName = userList[socket.id]
		delete userList[socket.id];
		// 离开
		io.emit("upRoom",userName,Object.keys(userList).length,false);
	})
})
app.post("/login",(req,res)=>{
	if(Object.values(userList).includes(req.body.userName)){
		res.json({
			ok:-1,// 聊天室中已经存在该用户
		})
	}else{
		res.json({
			ok:1// 登陆成功
		})
	}
	
})
app.get("/userList",(req,res)=>{
	res.json(userList);
})
app.use(express.static(__dirname));
httpServer.listen(80,function(){
	console.log('success');
})
